#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查真实HAI API调用需求
"""

import os
import sys
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

# 加载环境变量
from dotenv import load_dotenv
load_dotenv()

def check_hai_api_requirements():
    """检查HAI API调用需求"""
    print("🔍 检查真实HAI API调用需求")
    print("=" * 50)
    
    try:
        # 尝试导入腾讯云SDK
        from tencentcloud.common import credential
        from tencentcloud.hai.v20230812 import hai_client, models
        from tencentcloud.common.profile.client_profile import ClientProfile
        from tencentcloud.common.profile.http_profile import HttpProfile
        
        print("✅ 腾讯云SDK导入成功")
        
        # 创建凭证
        cred = credential.Credential(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY')
        )
        
        # 创建客户端
        profile = ClientProfile()
        profile.httpProfile = HttpProfile()
        profile.httpProfile.endpoint = "hai.tencentcloudapi.com"
        
        client = hai_client.HaiClient(cred, "ap-beijing", profile)
        
        print("✅ HAI客户端创建成功")
        
        # 检查可用地域
        print("\n🌍 检查可用地域...")
        try:
            req = models.DescribeRegionsRequest()
            resp = client.DescribeRegions(req)
            print(f"可用地域: {resp}")
        except Exception as e:
            print(f"地域查询失败: {e}")
        
        # 检查实例类型
        print("\n🖥️ 检查实例类型...")
        try:
            req = models.DescribeInstanceTypesRequest()
            resp = client.DescribeInstanceTypes(req)
            print(f"实例类型: {resp}")
        except Exception as e:
            print(f"实例类型查询失败: {e}")
        
        # 尝试创建实例（不执行，只检查参数）
        print("\n🏗️ 检查创建实例所需参数...")
        try:
            req = models.RunInstancesRequest()
            print("RunInstancesRequest 所需参数:")
            
            # 检查请求对象的属性
            attrs = [attr for attr in dir(req) if not attr.startswith('_')]
            for attr in attrs:
                print(f"  - {attr}")
                
        except Exception as e:
            print(f"参数检查失败: {e}")
        
        return True
        
    except ImportError as e:
        print(f"❌ SDK导入失败: {e}")
        return False
    except Exception as e:
        print(f"❌ API检查失败: {e}")
        return False

def check_application_id():
    """检查ApplicationId参数"""
    print("\n📋 检查ApplicationId参数需求...")
    
    try:
        from tencentcloud.hai.v20230812 import models
        
        # 创建请求对象
        req = models.RunInstancesRequest()
        
        print("RunInstancesRequest 可能需要的参数:")
        print("  - ApplicationId (应用ID)")
        print("  - InstanceName (实例名称)")
        print("  - InstanceType (实例类型)")
        print("  - ImageId (镜像ID)")
        print("  - Region (地域)")
        print("  - InstanceCount (实例数量)")
        
        # 尝试设置ApplicationId
        try:
            # 使用我们配置的真实应用ID
            req.ApplicationId = "app-oefac6i2"
            req.InstanceName = "test-real-instance"
            req.InstanceCount = 1
            req.Region = "ap-beijing"
            
            print(f"\n✅ 请求参数设置成功:")
            print(f"  ApplicationId: {req.ApplicationId}")
            print(f"  InstanceName: {req.InstanceName}")
            print(f"  InstanceCount: {req.InstanceCount}")
            print(f"  Region: {req.Region}")
            
            return True
            
        except Exception as e:
            print(f"❌ 参数设置失败: {e}")
            return False
            
    except Exception as e:
        print(f"❌ 检查失败: {e}")
        return False

def main():
    """主函数"""
    print("🚀 检查真实HAI API调用需求")
    print("=" * 60)
    
    # 检查环境变量
    secret_id = os.getenv('TENCENT_SECRET_ID')
    secret_key = os.getenv('TENCENT_SECRET_KEY')
    
    if not secret_id or not secret_key:
        print("❌ 环境变量未配置")
        return False
    
    print(f"Secret ID: {secret_id[:10]}...")
    print(f"Secret Key: {secret_key[:10]}...")
    
    # 检查API需求
    if check_hai_api_requirements():
        print("\n✅ API环境检查通过")
    else:
        print("\n❌ API环境检查失败")
        return False
    
    # 检查ApplicationId参数
    if check_application_id():
        print("\n✅ 参数检查通过")
    else:
        print("\n❌ 参数检查失败")
        return False
    
    print("\n📋 总结:")
    print("要创建真实的HAI实例，需要:")
    print("1. ✅ 有效的腾讯云密钥")
    print("2. ✅ HAI服务权限")
    print("3. ✅ ApplicationId (应用ID)")
    print("4. ✅ InstanceName (实例名称)")
    print("5. ✅ 其他必需参数")
    
    print("\n💡 建议:")
    print("- 使用真实的应用ID: app-oefac6i2")
    print("- 提供完整的实例创建参数")
    print("- 确保有足够的权限和配额")
    
    return True

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
